﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Service.cs" company="Jim Liddell">
//   Copyright © Jim Liddell. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace TeamBuildBunnyWindowsService
{
    #region Usings

    using System;
    using System.Diagnostics;
    using System.ServiceModel;
    using System.ServiceProcess;

    using TeamBuildBunny;

    #endregion

    /// <summary>
    /// The service.
    /// </summary>
    public partial class Service : ServiceBase
    {
        #region Constants and Fields

        /// <summary>
        /// Host for the <see cref="BuildCompletionEndpoint"/>.
        /// </summary>
        private readonly ServiceHost buildCompletionServiceHost;

        /// <summary>
        /// Host for the <see cref="CheckInEndpoint"/>.
        /// </summary>
        private readonly ServiceHost checkInServiceHost;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Service"/> class.
        /// </summary>
        public Service()
        {
            this.InitializeComponent();

            this.buildCompletionServiceHost = new ServiceHost(typeof(BuildCompletionEndpoint));
            this.checkInServiceHost = new ServiceHost(typeof(CheckInEndpoint));
        }

        #endregion

        #region Methods

        /// <summary>
        /// Opens the hosts listening for events.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            try
            {
                this.buildCompletionServiceHost.Open();
                this.checkInServiceHost.Open();
            }
            catch (Exception ex)
            {
                Trace.TraceError("An unhandled exception occured in Team Build Bunny. The Exception was '{0}'.", ex);

                throw;
            }
        }

        /// <summary>
        /// Closes the hosts.
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                this.checkInServiceHost.Close();
                this.buildCompletionServiceHost.Close();
            }
            catch (Exception ex)
            {
                Trace.TraceError("An unhandled exception occured in Team Build Bunny. The Exception was '{0}'.", ex);

                throw;
            }
        }

        #endregion
    }
}